import pdfplumber
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl.utils.dataframe import dataframe_to_rows
import re
import tkinter as tk
from tkinter import filedialog
import os

def extract_table_from_pdf(input_file_path, output_file_path):
    # 创建一个新的Excel工作簿
    workbook = openpyxl.Workbook()
    sheet = workbook.active

    with pdfplumber.open(input_file_path) as pdf:
        # 遍历每一页
        for page in pdf.pages:
            # 提取当前页中的所有表格
            tables = page.extract_tables()

            for table in tables:
                # 遍历表格的每一行
                for row in table:
                    # 将每一行的数据写入Excel中的新行中
                    new_row = []
                    for cell in row:
                        # 检查单元格类型是否为字符串
                        if isinstance(cell, str):
                            # 删除换行符、制表符和空格
                            cell_text = re.sub(r'[\n\t\s]', '', cell)
                            new_row.append(cell_text)
                        else:
                            new_row.append(cell)
                    sheet.append(new_row)

    # 调整列宽以适应内容
    for column in sheet.columns:
        max_length = 0
        column_letter = get_column_letter(column[0].column)
        for cell in column:
            try:
                if len(str(cell.value)) > max_length:
                    max_length = len(cell.value)
            except TypeError:
                pass
        adjusted_width = (max_length + 2) * 1.2
        sheet.column_dimensions[column_letter].width = adjusted_width

    # 修改输出文件路径的扩展名为xlsx
    output_file_path = os.path.splitext(output_file_path)[0] + '.xlsx'
    count=1

    while os.path.exists(output_file_path):
                output_file_path = os.path.splitext(output_file_path)[0] + f'_{count}.xlsx'
                count += 1

    # 保存Excel文件
    workbook.save(output_file_path)
    result_label.config(text="表格已成功写入Excel文件！", fg="green")


# 创建GUI
def browse_pdf():
    pdf_path = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
    entry_pdf.delete(0, tk.END)
    entry_pdf.insert(0, pdf_path)

def select_output_folder():
    output_folder = filedialog.askdirectory()
    entry_output.delete(0, tk.END)
    entry_output.insert(0, output_folder)

def process_table():
    input_file_path = entry_pdf.get().strip()
    output_folder = entry_output.get().strip()

    if not os.path.isfile(input_file_path):
        result_label.config(text="输入文件不存在！", fg="red")
        return

    if not output_folder:
        # 如果输出文件夹为空，则使用输入文件路径作为默认输出文件夹
        output_folder = os.path.dirname(input_file_path)
        entry_output.delete(0, tk.END)
        entry_output.insert(0, output_folder)

    if not os.path.isdir(output_folder):
        result_label.config(text="输出文件夹不存在！", fg="red")
        return

    # 提取输入文件的文件名和扩展名
    file_name, ext = os.path.splitext(os.path.basename(input_file_path))
  
    # 构建输出文件路径
    output_file_path = os.path.join(output_folder, file_name + ".xlsx")

    # 调用提取表格的函数
    extract_table_from_pdf(input_file_path, output_file_path)


# 创建Tkinter窗口
window = tk.Tk()
window.title("PDF表格提取copyright@EY Halit He")

# 创建PDF文件选择标签和输入框
label_pdf = tk.Label(window, text="选择要转换的PDF文件:")
label_pdf.pack()

entry_pdf = tk.Entry(window, width=50)
entry_pdf.pack()

button_browse = tk.Button(window, text="浏览文件", command=browse_pdf)
button_browse.pack()

# 创建输出文件夹选择标签和输入框
label_output = tk.Label(window, text="选择输出文件夹:")
label_output.pack()

entry_output = tk.Entry(window, width=50)
entry_output.pack()

gui_option_frame = tk.Frame(window)
gui_option_frame.pack()

gui_option_label = tk.Label(gui_option_frame, text="是否使用默认输出路径?")
gui_option_label.grid(row=0, column=0)

gui_option_var = tk.StringVar()
gui_option_var.set("是")  # 默认选中“是”

gui_radio_button_yes = tk.Radiobutton(gui_option_frame, text="是", variable=gui_option_var, value="是")
gui_radio_button_yes.grid(row=0, column=1)

gui_radio_button_no = tk.Radiobutton(gui_option_frame, text="否", variable=gui_option_var, value="否")
gui_radio_button_no.grid(row=0, column=2)

button_select_output = tk.Button(window, text="选择输出文件夹", command=select_output_folder)
button_select_output.pack()

# 创建处理表格按钮
button_process = tk.Button(window, text="处理表格", command=process_table)
button_process.pack()

result_label = tk.Label(window, text="")
result_label.pack()

# 根据GUI选项更新输出路径输入框的状态和按钮的状态
def update_output_dir_entry_state(*args):
    if gui_option_var.get() == "是":
        entry_output.delete(0, tk.END)
        input_file_path = entry_pdf.get().strip()

        # 将输出文件路径设置为输入文件路径的文件夹路径
        output_folder = os.path.dirname(input_file_path)
        entry_output.insert(0, output_folder)

        # 禁用选择输出文件夹按钮
        button_select_output.config(state="disabled")
        entry_output.config(state="disabled")
    else:
        # 允许选择输出文件夹按钮
        button_select_output.config(state="normal")
        entry_output.config(state="normal")

gui_option_var.trace("w", update_output_dir_entry_state)

# 初始化时设置默认为“是”
gui_option_var.set("是")
update_output_dir_entry_state()  # 更新输出路径输入框和按钮的状态

def open_link(event):
    webbrowser.open("https://gitee.com/halit_he/audit-copilot")
    
link_label = tk.Label(window, text="点击查看更多工具", fg="blue", cursor="hand2", font=("Arial", 10, "underline"))
link_label.pack(side="bottom", anchor="sw")

link_label.bind("<Button-1>", open_link)

window.mainloop()
